﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Epsilon.Expr;
using System.IO;

namespace Epsilon.Output
{
    public class ProgramWriter
    {
        List<Process> processes = null;
        string main = null;

        public ProgramWriter(List<Process> p, string m)
        {
            processes = p;
            main = m;
        }

        public void WriteFiles()
        {
            foreach (Process p in processes)
            {
                Writer writer = new Writer(p);
                writer.Write();
            }

            Console.WriteLine("Writing main program file: " + main);
            StreamWriter wr = new StreamWriter(main);
            try
            {
                wr.WriteLine();
                wr.WriteLine("-module(program).");
                wr.WriteLine("-export([main/0]).");
                wr.WriteLine();
                wr.WriteLine("main() ->");
                for (int i = 0; i < processes.Count; i++)
                {
                    wr.Write("  register(" + processes[i].Name + ", spawn(fun " + processes[i].Name + ":main/0))");
                    if (i < processes.Count - 1)
                        wr.WriteLine(",");
                    else
                        wr.WriteLine(".");
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                wr.Close();
            }
        }
    }
}
